package rest

import (
	"gorm_demo/pkg/logger"
	"gorm_demo/pkg/models"
	"gorm_demo/pkg/service"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
)

type userCtrl struct {
	log logger.LogInfoFormat
	svc service.AuthUserService
}

func NewUserCtrl(log logger.LogInfoFormat, svc service.AuthUserService) *userCtrl {
	return &userCtrl{log, svc}
}

func (u *userCtrl) List(ctx *gin.Context) {
	users := u.svc.List()
	u.log.Info(g.Export(users))
	if len(users) == 0 {
		ctx.Status(http.StatusNoContent)
		return
	}
	ctx.JSON(http.StatusOK, users)
}

func (u *userCtrl) GetById(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))

	user, err := u.svc.GetById(int32(id))
	if user == nil || err != nil {
		ctx.Status(http.StatusNotFound)
		return
	}
	ctx.JSON(http.StatusOK, user)
}

func (u *userCtrl) Create(ctx *gin.Context) {
	var user models.AuthUser
	if err := ctx.ShouldBindJSON(&user); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	user.DateJoined = gtime.Now()
	obj, err := u.svc.Create(user)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, "")
		return
	}
	ctx.JSON(http.StatusCreated, obj)
}

func (u *userCtrl) Update(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))

	var user models.AuthUser
	if err := ctx.ShouldBindJSON(&user); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	user.Id = int32(id)
	u.svc.Update(user, map[string]interface{}{"id": 1})
	ctx.Status(http.StatusOK)
}

func (u *userCtrl) Delete(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))

	user, err := u.svc.GetById(int32(id))
	if user == nil || err != nil {
		ctx.Status(http.StatusNotFound)
		return
	}
	u.svc.Delete(*user)
	ctx.Status(http.StatusNoContent)
}
